package cn.ztydata.teachingsystem.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 * 字符串编码工具类
 * Created by chenxin on 2014/7/1.
 */
public class StringCodeUtil  {
    private static final Logger logger = LoggerFactory.getLogger(StringCodeUtil.class); //日志记录器

    public static final String UTF8 = "utf-8";

    /**
     * 处理get中文参数乱码
     * @param arg 参数
     * @param code 指定编码
     * @return String
     *
     * @author cx
     * @since 2014-04-29
     */
    public static String urlParamTransCode(String arg, String code) {
        if (arg == null || arg.isEmpty()) {
            logger.debug("参数为空:arg == null || arg.isEmpty()");
            return "";
        }

        try {
            logger.debug("处理get中文参数乱码");
            return new String(arg.getBytes("ISO-8859-1"), code);
        } catch (UnsupportedEncodingException ex) {
            logger.warn("无效字符集:" + code);

            return "";
        }
    }

    /**
     * 字符串URL解码
     * @param arg 参数
     * @param code 指定编码
     * @return String
     *
     * @author cx
     * @since 2014-05-09
     */
    public static String urlDecode(String arg, String code) {
        try {
            return URLDecoder.decode(arg, code);
        } catch (UnsupportedEncodingException ex) {
            logger.warn("无效字符集:" + code);

            return "";
        }
    }

    /**
     * 字符串URL编码
     * @param arg 参数
     * @param code 指定编码
     * @return String
     *
     * @author cx
     * @since 2014-05-09
     */
    public static String urlEncode(String arg, String code) {
        try {
            return URLEncoder.encode(arg, code);
        } catch (UnsupportedEncodingException ex) {
            logger.warn("无效字符集:" + code);

            return "";
        }
    }

}
